//
//  MusicDetailViewController.swift
//  YYMusicDemo
//
//  Created by yuanyue on 2018/4/26.
//  Copyright © 2018年 yuanyue. All rights reserved.
//

private let MusicLrcCellIdentifier = "MusicLrcCellIdentifier"

import UIKit

class MusicDetailViewController: UIViewController, UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var musicNameLabel: UILabel!
    @IBOutlet weak var singerLabel: UILabel!
    
    @IBOutlet weak var singerIconImgView: UIImageView!
    @IBOutlet weak var lyricsLabel: UILabel!    //
    
    @IBOutlet weak var scrollView: UIScrollView!

    var musicLrcModels = [MusicLrcModel]()
    
    @IBOutlet weak var lrcTableView: UITableView!
    
    @IBOutlet weak var slider: UISlider!        //
    @IBOutlet weak var startTimeLabel: UILabel! //
    @IBOutlet weak var endTimeLabel: UILabel!
    @IBOutlet weak var playButton: UIButton!
    
    var model : MusicDetailModel?
    var lrcModel : MusicLrcModel?
    var timer : Timer?
    var updateLrcLink : CADisplayLink?
    
    var scrollRow = 0 {
        didSet {
            let indexPath : IndexPath = IndexPath(row: scrollRow, section: 0)
            lrcTableView.scrollToRow(at: indexPath, at: .middle, animated: true)
        }
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.cyan
        
        setupScrollView()
        setupSlider()
        updateView()

        setupTableView()
        addLrcLink()
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setupScrollView() -> () {
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
        scrollView.showsHorizontalScrollIndicator = false
    }
    
    func setupSlider() -> () {
        slider.setThumbImage(UIImage.init(named: "player_slider_playback_thumb"), for: .normal)
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        singerIconImgView.layer.cornerRadius = singerIconImgView.frame.size.width / 2
        singerIconImgView.layer.masksToBounds = true
        lrcTableView.contentInset = UIEdgeInsets(top: lrcTableView.frame.size.height * 0.5, left: 0, bottom: lrcTableView.frame.size.height * 0.5, right: 0)

    }
    
    func addLrcLink() -> () {
        updateLrcLink = CADisplayLink(target: self, selector: #selector(MusicDetailViewController.updateLrc))
        updateLrcLink?.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
    }
    
    func removeLrcLink() -> () {
        updateLrcLink?.invalidate()
        updateLrcLink = nil
    }
    
    @objc func updateLrc() -> () {
        model = PlayMusicManager.shareManager.getCurrentMusicDetail()
        let time = model?.startTime
        lyricsLabel.text = lrcModel?.lrcContent
        

        print(lyricsLabel.text ?? "")
        print("0000")
    }
    
    @IBAction func changeSliderValue(_ sender: UISlider) {
        print(sender.value)

        PlayMusicManager.shareManager.breakpointPlay(time: TimeInterval(sender.value))
        
    }
    
    @IBAction func close(_ sender: UIButton) {
        self.dismiss(animated: true) {}
    }
    
    // 暂停/开始
    @IBAction func playOrPauseAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            PlayMusicManager.shareManager.playCurrentMusic()
            resumeAnimation()
        } else {
            PlayMusicManager.shareManager.pauseMusic()
            pauseAnimation()
        }
    }
    
    // 上一首
    @IBAction func beforeMusic(_ sender: UIButton) {
        PlayMusicManager.shareManager.playBeginMusic()
        updateView()
    }
    
    // 下一首
    @IBAction func nextMusic(_ sender: UIButton) {
        PlayMusicManager.shareManager.playNextMusic()
        updateView()
    }
    
    // 更新view部分控件
    func updateView() -> () {
        model = PlayMusicManager.shareManager.getCurrentMusicDetail()
        if model != nil {
            musicNameLabel.text = model?.model?.name
            singerLabel.text = model?.model?.singer
            singerIconImgView.image = UIImage.init(named: (model?.model?.icon)!)
            endTimeLabel.text = TimeTool.getFormetTimer(timer: (model?.totalTime)!)
            slider.minimumValue = 0
            slider.maximumValue = Float((model?.totalTime)!)
            
            starAnimation()
            if (model?.isPlaying)! {
                resumeAnimation()
            }else {
                pauseAnimation()
            }
            
            musicLrcModels = PlayMusicManager.shareManager.getMusicLyrics(lyricName: (model?.model?.lrcname)!)
            lrcTableView.reloadData()

        }
    }
    
    // 每秒更新
    @objc func updateLyrics() -> () {
        model = PlayMusicManager.shareManager.getCurrentMusicDetail()
        model?.startTime = (model?.startTime)! + Double(0.01)
        
        model = PlayMusicManager.shareManager.getCurrentMusicDetail()
        if model != nil {
            startTimeLabel.text = TimeTool.getFormetTimer(timer: (model?.startTime)!)
            slider.value = Float((model?.startTime)!)
        }
        playButton.isSelected = (model?.isPlaying)!
        
    }
    
    func addTimer() -> () {
        timer = Timer(timeInterval: 1, target: self, selector: #selector(MusicDetailViewController.updateLyrics), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: .commonModes)
    }
    
    func removeTimer() -> () {
        timer?.invalidate()
        timer = nil
    }
    
    override func viewWillAppear(_ animated: Bool) {
        addTimer()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        removeTimer()
    }
    
    // 开始旋转动画
    func starAnimation() -> () {
        
        singerIconImgView.layer.removeAnimation(forKey: "rotationAnimation")
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotationAnimation.toValue = Double.pi * 2.0
        rotationAnimation.duration = 15
        rotationAnimation.isCumulative = true
        rotationAnimation.repeatCount = MAXFLOAT
        rotationAnimation.isRemovedOnCompletion = false
        singerIconImgView.layer.add(rotationAnimation, forKey: "rotationAnimation")
    }
    
    // 暂停旋转动画
    func pauseAnimation() -> () {
        
        //1.取出当前时间，转成动画暂停的时间
        let pauseTime = singerIconImgView.layer.convertTime(CACurrentMediaTime(), from: nil)
        
        //2.设置动画的时间偏移量，指定时间偏移量的目的是让动画定格在该时间点的位置
        singerIconImgView.layer.timeOffset = pauseTime;

        //3.将动画的运行速度设置为0， 默认的运行速度是1.0
        singerIconImgView.layer.speed = 0;
    }
    
    // 恢复旋转动画
    func resumeAnimation() -> () {
        
        //1.将动画的时间偏移量作为暂停的时间点
        let pauseTime = singerIconImgView.layer.timeOffset
        
        //2.计算出开始时间
        let begin = CACurrentMediaTime() - pauseTime
        
        singerIconImgView.layer.timeOffset = 0
        singerIconImgView.layer.beginTime = begin
        singerIconImgView.layer.speed = 1
    
    }
}

// scrollView 代理
extension MusicDetailViewController {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let x = scrollView.contentOffset.x
        let radio = 1 - x / scrollView.frame.size.width
        
        singerIconImgView.alpha = radio
        lyricsLabel.alpha = radio
    }
}

// tableview 代理
extension MusicDetailViewController {
    func setupTableView() -> () {
        self.lrcTableView.tableFooterView = UIView()
        self.lrcTableView.register(UINib.init(nibName: "MusicLrcCell", bundle: nil), forCellReuseIdentifier: MusicLrcCellIdentifier)
        self.lrcTableView.rowHeight = 30
        self.lrcTableView.showsVerticalScrollIndicator = false
        self.lrcTableView.separatorStyle = .none
        self.lrcTableView.allowsSelection = false
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.musicLrcModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MusicLrcCellIdentifier, for: indexPath) as! MusicLrcCell
        
        let model : MusicLrcModel = self.musicLrcModels[indexPath.row]
        lrcModel = model
        cell.model = model
        return cell
    }
}
